package com.jacob.cloud.mall.user.service.impl;

import com.jacob.cloud.mall.common.exception.MallException;
import com.jacob.cloud.mall.common.exception.MallExceptionEnum;
import com.jacob.cloud.mall.common.util.MD5Utils;
import com.jacob.cloud.mall.user.model.dao.UserMapper;
import com.jacob.cloud.mall.user.model.pojo.User;
import com.jacob.cloud.mall.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

/**
 * 用户Service实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param userName 用户名
     * @param password 用户密码
     */
    @Override
    public void register(String userName, String password) throws MallException {
        // 判断用户名是否已存在
        if (userMapper.hasOneByName(userName) > 0){
            throw new MallException(MallExceptionEnum.NAME_EXIST);
        }
        User user = new User();
        user.setUsername(userName);
        try {
            // 加密密码
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 插入数据库
        int count = userMapper.insertSelective(user);
        if (count == 0) {
            throw new MallException(MallExceptionEnum.INSERT_FAIL);
        }
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     */
    @Override
    public User login(String username, String password) throws MallException {
        String md5Str = null;
        try {
            // 获取加密后的密码
            md5Str = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 从数据中获取对应用户信息
        User user = userMapper.selectLogin(username, md5Str);
        if (user == null) {
            throw new MallException(MallExceptionEnum.WRONG_PASS);
        }

        return user;
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     */
    @Override
    public void updateInfo(User user) throws MallException {
        // 更新个性签名
        int updateCount = userMapper.updateByPrimaryKeySelective(user);

        if (updateCount < 1) {
            throw new MallException(MallExceptionEnum.UPDATE_FAIL);
        }
    }

    /**
     * 判断用户是否是管理员
     * @param user 用户信息
     */
    @Override
    public boolean checkAdminRole(User user) {
        return user.getRole().equals(2);
    }
}
